/*
 * ------------------------------------------------------------------
 * Copyright © 2017 Hangzhou DtDream Technology Co.,Lt d. All rights reserved.
 * ------------------------------------------------------------------
 *       Product:
 *   Module Name:
 *  Date Created: 2023/7/7
 *   Description:
 * ------------------------------------------------------------------
 * Modification History
 * DATE            Name           Description
 * ------------------------------------------------------------------
 * 2023/7/7    小谷 g2038          created
 * ------------------------------------------------------------------
 */
package com.gujh.security.authentication.jwt;

import cn.hutool.jwt.JWTUtil;
import com.gujh.security.model.Res;
import com.gujh.security.util.ResponseUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    /**
     * 登录成功后直接返回 JWT
     *
     * @param request        请求
     * @param response       响应
     * @param authentication 成功认证的用户信息
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        // JWT信息
        Map<String, Object> jwtMap = new HashMap<>();
        jwtMap.put("username", authentication.getName()); // 用户名作为用户唯一标识，实际开发可以使用 用户ID
        jwtMap.put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60); // 过期时间，一个小时后过期
        // 创建令牌
        String token = JWTUtil.createToken(jwtMap, "key".getBytes());
        // 响应数据
        ResponseUtil.response(response, Res.success(token), HttpStatus.OK);
    }
}

